package com.leecode.exercise;

public class 动态规划_02_最小路径和 {
    public static void main(String[] args) {
        int[][] grid = {
                {1, 1, 1},
                {1, 5, 1},
                {4, 2, 1}
        };

        // m=3,n=3 , m*n=3*3

        动态规划_02_最小路径和 solution = new 动态规划_02_最小路径和();
        int result = solution.minPathSum(grid);
        System.out.println("最小路径和为：" + result);
    }


    public int minPathSum(int[][] grid) {

        //边界
        if (grid.length == 0) {
            return 0;
        }

        int m = grid.length; //行
        int n = grid[0].length; //列

        //定义一个数组存放路径之和
        int[][] dp = new int[m][n];

        dp[0][0] = grid[0][0];

        //初始化第一行，累加和
        for (int i = 1; i < m; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }

        //初始化第一列，累加和
        for (int j = 1; j < n; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }

        //其它元素的累加和
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
            }
        }

        return dp[m - 1][n - 1];
    }


}
